﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

using System.Management.Automation;
using CrystalDecisions.Enterprise;
using CrystalDecisions.Enterprise.Desktop;

namespace BO.Management.PowerShell
{
    [Cmdlet(VerbsCommon.Set, "ObjectLimit", DefaultParameterSetName = CONNECT_SECWINAD)]
    public class SetObjectLimit : BaseActionObject<ContentGenericProvider, InfoObject>
    {

        [Parameter(Mandatory = true, ValueFromPipeline = true)]
        [ValidateNotNullOrEmpty]
        public Int32 MaxInstance { get; set; }


        public override ContentGenericProvider GetProvider()
        {
            return new ContentGenericProvider(this.LogonProvider);
        }


        public override void WorkWithSingleObject(InfoObject boeObject)
        {
            if (boeObject != null)
            {
                WriteVerbose(String.Format("Extract Default Limit for the Folder {0}", boeObject.Title));
                SecurityInfoProvider infoProvider = new SecurityInfoProvider();
                SecurityLimit limit = infoProvider.GetDefaultLimit(boeObject);
                if (limit == null)
                {
                    WriteVerbose(String.Format("No Default Limit exist for the Folder {0}, Add a new Limit at {1}", boeObject.Title,this.MaxInstance));
                    SecurityLimits limitContainer = infoProvider.GetDefaultLimitContainer(boeObject);
                    limit = limitContainer.Add(SecurityInfoProvider.MAXINSTANCEPEROBJECTID, this.MaxInstance);
                }
                else
                {
                    WriteVerbose(String.Format("Current Limit for the Folder {0} is {1}, will be changed to {2}", boeObject.Title,limit.Value, this.MaxInstance));
                    limit.Value = this.MaxInstance;
                }
                BoeProvider.Commit(boeObject);
                this.WriteObject(limit);
            }
        }

    }
}
